package com.qf.ability.notify.service.impl;

import com.qf.ability.notify.service.IEmailService;
import com.qf.data.notify.entity.Email;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;

/**
 * author Ken
 * create_time 2022/11/16
 */
@Service
@Slf4j
public class EmailServiceImpl implements IEmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public boolean sendEmail(Email email) {
        log.debug("[send email] 发送邮件 - {}", email);

        try {
            //创建一个原生的邮件对象
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            //对原生对象进行二次封装
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            //设置邮件的标题
            mimeMessageHelper.setSubject(email.getSubject());
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(email.getTos().toArray(new String[0]));//接收方
            //mimeMessageHelper.setCc();//抄送方
            //mimeMessageHelper.setBcc();//密送方
            mimeMessageHelper.setSentDate(email.getSendTime());
            mimeMessageHelper.setText(email.getContent(), true);
            //发送邮件
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
